package com.qunshang.common;

import static com.mchange.v2.c3p0.impl.C3P0Defaults.user;
import com.mycompany.yourtrade.model.Seller;
import com.mycompany.yourtrade.model.UserBean;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import nl.captcha.Captcha;

/**
 *
 * @author xiaoguang
 */
public class SessionUtils {
    
     static String SESSION_KEY = "SellerSession";
     
     public static String getSellerId(final HttpServletRequest request) {
        SellerSession session = getSession(request);
        if (session == null) {
            return null;
        }

        Seller sell = session.getSell();
        return sell == null ? null : sell.getId();
    }

    public static Seller getSeller(final HttpServletRequest request) {
        SellerSession session = getSession(request);
        if (session == null) {
            return null;
        }
        return session.getSell();
    }

    public static void setSession(final HttpServletRequest request,
                                  final SellerSession session) {
        request.getSession().setAttribute(SESSION_KEY, session);
    }

    public static SellerSession getSession(final HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        HttpSession httpSession = request.getSession(false);
        return httpSession == null ? null : getSession(httpSession);
    }

    public static SellerSession getSession(final HttpSession httpSession) {
        if (httpSession == null) {
            return null;
        }
        return (SellerSession) httpSession.getAttribute(SESSION_KEY);
    }

    /**
     * 获取保存在Session中的对象
     *
     * @param <T>
     * @param request
     * @param name 在Session中的键值
     * @param clazz 对象类型
     * @param remove 是否从Session中移除
     * @return 返回对象 or null
     */
    public static <T> T getAttribute(final HttpServletRequest request,
                                     final String name,
                                     final Class<T> clazz,
                                     final boolean remove) {
        T result = null;
        HttpSession session = request.getSession();
        if (session.getAttribute(name) != null) {
            result = (T) session.getAttribute(name);
            if (remove) {
                session.removeAttribute(name);
            }
        }
        return result;
    }
    /**
     * 判断验证码是否正确
     *
     * @param request
     * @param captcha
     * @return
     */
    public static boolean validateCaptcha(final HttpServletRequest request,
                                          final String captcha) {
        Captcha c = (Captcha) SessionUtils.getAttribute(request, Captcha.NAME, Captcha.class, false);
        return c.isCorrect(captcha);
    }
}
